// 视图层 - 负责界面展示
class StudentView {
    constructor() {
        this.scene = null;
        this.camera = null;
        this.renderer = null;
        this.sphere = null;
        this.studentNodes = [];
        this.animationId = null;
        this.isAnimating = false;
        this.rotationSpeed = 0.015; // 0.005 * 3 = 0.015，将转动速度乘以3
        this.isRolling = false;
        this.sphereGroup = null; // 球体组，包含球体和所有名字
        
        this.initThreeJS();
    }

    // 初始化Three.js场景
    initThreeJS() {
        const container = document.getElementById('threejs-container');
        const width = container.clientWidth;
        const height = container.clientHeight;

        // 创建场景
        this.scene = new THREE.Scene();
        this.scene.background = new THREE.Color(0x0a0a0a);

        // 创建相机
        this.camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
        this.camera.position.z = 45; // 调整相机距离以适应更大的球体

        // 创建渲染器
        this.renderer = new THREE.WebGLRenderer({ antialias: true });
        this.renderer.setSize(width, height);
        this.renderer.shadowMap.enabled = true;
        this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
        container.appendChild(this.renderer.domElement);

        // 添加光源
        const ambientLight = new THREE.AmbientLight(0xffffff, 0.4);
        this.scene.add(ambientLight);

        const directionalLight = new THREE.DirectionalLight(0xffffff, 0.6);
        directionalLight.position.set(10, 10, 5);
        directionalLight.castShadow = true;
        this.scene.add(directionalLight);

        // 创建球体组
        this.sphereGroup = new THREE.Group();
        this.scene.add(this.sphereGroup);

        // 创建基础球体
        this.createBaseSphere();

        // 开始渲染循环
        this.animate();

        // 处理窗口大小变化
        window.addEventListener('resize', () => this.onWindowResize());
    }

    // 创建基础球体
    createBaseSphere() {
        const geometry = new THREE.SphereGeometry(19.5, 64, 64); // 15 * 1.3 = 19.5
        const material = new THREE.MeshPhongMaterial({ 
            color: 0x1a1a2e, 
            transparent: true, 
            opacity: 0.1,
            wireframe: true
        });
        this.sphere = new THREE.Mesh(geometry, material);
        this.sphereGroup.add(this.sphere);
    }

    // 更新学生节点
    updateStudentNodes(students) {
        // 清除现有节点
        this.studentNodes.forEach(node => {
            this.sphereGroup.remove(node);
        });
        this.studentNodes = [];

        // 创建新节点
        students.forEach((student, index) => {
            const node = this.createStudentNode(student, index, students.length);
            this.studentNodes.push(node);
            this.sphereGroup.add(node);
        });
    }

    // 创建学生节点
    createStudentNode(name, index, total) {
        // 使用斐波那契螺旋分布算法
        const phi = Math.acos(1 - 2 * index / total);
        const theta = Math.PI * (1 + Math.sqrt(5)) * index;
        
        const radius = 20.8; // 16 * 1.3 = 20.8，名字分布半径，与放大后的球体表面对应
        const x = radius * Math.sin(phi) * Math.cos(theta);
        const y = radius * Math.sin(phi) * Math.sin(theta); // 移除了-8的偏移，让名字回到球体表面
        const z = radius * Math.cos(phi);

        // 创建文字标签作为主要显示元素
        const textSprite = this.createTextSprite(name);
        textSprite.position.set(x, y, z);
        textSprite.userData = { 
            name: name, 
            originalPosition: new THREE.Vector3(x, y, z),
            isSelected: false
        };
        
        return textSprite;
    }

    // 创建文字精灵
    createTextSprite(text) {
        const canvas = document.createElement('canvas');
        const context = canvas.getContext('2d');
        canvas.width = 512;
        canvas.height = 256;
        
        // 清除画布
        context.clearRect(0, 0, canvas.width, canvas.height);
        
        // 设置字体样式
        context.fillStyle = '#00ffff';
        context.font = 'bold 48px Arial';
        context.textAlign = 'center';
        context.textBaseline = 'middle';
        
        // 绘制文字
        context.fillText(text, canvas.width / 2, canvas.height / 2);
        
        const texture = new THREE.CanvasTexture(canvas);
        const spriteMaterial = new THREE.SpriteMaterial({ map: texture });
        const sprite = new THREE.Sprite(spriteMaterial);
        sprite.scale.set(6, 3, 1);
        
        return sprite;
    }

    // 开始滚动动画
    startRollingAnimation() {
        this.isAnimating = true;
        this.isRolling = true;
        this.rollAnimation();
    }

    // 停止滚动动画
    stopRollingAnimation() {
        this.isAnimating = false;
        this.isRolling = false;
    }

    // 滚动动画
    rollAnimation() {
        if (!this.isAnimating) return;
        
        // 随机高亮一个节点（仅在下方显示区域显示）
        if (this.studentNodes.length > 0) {
            const randomIndex = Math.floor(Math.random() * this.studentNodes.length);
            const selectedNode = this.studentNodes[randomIndex];
            
            // 更新选中学生显示
            this.updateSelectedStudent(selectedNode.userData.name);
        }
        
        // 继续动画
        setTimeout(() => this.rollAnimation(), 100);
    }

    // 高亮选中的学生
    highlightStudent(studentName) {
        // 球上的名字不需要特殊高亮，只更新下方显示
        this.updateSelectedStudent(studentName, true);
    }

    // 更新选中学生显示
    updateSelectedStudent(studentName, isFinal = false) {
        const selectedElement = document.getElementById('selectedStudent');
        const nameElement = selectedElement.querySelector('.student-name');
        
        if (studentName) {
            // 显示名字块
            selectedElement.classList.add('visible');
            nameElement.textContent = studentName;
            nameElement.style.textAlign = 'center';
            
            if (isFinal) {
                // 最终结果，添加线框，颜色与点击下方名字时一样
                selectedElement.classList.remove('rolling');
                selectedElement.classList.add('final-result');
                nameElement.style.color = '#ff6b6b'; // 与CSS中.selected-student.final-result .student-name的颜色一致
            } else {
                // 滚动过程中
                selectedElement.classList.add('rolling');
                selectedElement.classList.remove('final-result');
                nameElement.style.color = '#ff6b6b'; // 滚动时也使用相同的颜色
            }
        } else {
            // 没有名字时隐藏名字块
            selectedElement.classList.remove('visible', 'rolling', 'final-result');
            nameElement.textContent = '';
        }
    }

    // 更新学生列表显示
    updateStudentList(students) {
        const studentsGrid = document.getElementById('studentsGrid');
        const studentCount = document.getElementById('studentCount');
        
        if (studentCount) {
            studentCount.textContent = students.length;
        }
        
        if (studentsGrid) {
            studentsGrid.innerHTML = '';
            students.forEach(student => {
                const card = document.createElement('div');
                card.className = 'student-card';
                card.textContent = student;
                card.onclick = () => this.selectStudentCard(card, student);
                studentsGrid.appendChild(card);
            });
        }
    }

    // 选中学生卡片
    selectStudentCard(card, studentName) {
        // 移除其他卡片的选中状态
        document.querySelectorAll('.student-card').forEach(c => {
            c.classList.remove('selected');
        });
        
        // 添加选中状态
        card.classList.add('selected');
        
        // 高亮3D节点
        this.highlightStudent(studentName);
    }

    // 更新按钮状态
    updateButtonStates(isRolling) {
        const startBtn = document.getElementById('startBtn');
        const stopBtn = document.getElementById('stopBtn');
        
        startBtn.disabled = isRolling;
        stopBtn.disabled = !isRolling;
    }

    // 动画循环
    animate() {
        this.animationId = requestAnimationFrame(() => this.animate());
        
        // 旋转整个球体组（包含球体和所有名字）
        if (this.sphereGroup) {
            if (this.isRolling) {
                // 优化的旋转动画：更平滑的多轴旋转，减少抖动，速度乘以3
                this.sphereGroup.rotation.x += (0.02 + Math.sin(Date.now() * 0.001) * 0.01) * 3;
                this.sphereGroup.rotation.y += (0.03 + Math.cos(Date.now() * 0.0015) * 0.015) * 3;
                this.sphereGroup.rotation.z += (0.015 + Math.sin(Date.now() * 0.0008) * 0.008) * 3;
            } else {
                // 缓慢顺时针旋转，速度也乘以3
                this.sphereGroup.rotation.y += this.rotationSpeed;
            }
        }
        
        this.renderer.render(this.scene, this.camera);
    }

    // 处理窗口大小变化
    onWindowResize() {
        const container = document.getElementById('threejs-container');
        const width = container.clientWidth;
        const height = container.clientHeight;
        
        this.camera.aspect = width / height;
        this.camera.updateProjectionMatrix();
        this.renderer.setSize(width, height);
    }

    // 重置视图
    reset() {
        this.stopRollingAnimation();
        this.updateSelectedStudent(null);
        
        // 移除所有卡片的选中状态
        document.querySelectorAll('.student-card').forEach(card => {
            card.classList.remove('selected');
        });
    }
}